package com.sx.mvvmlibs.http.tools.encrypts;

import com.google.gson.Gson;
import com.sx.mvvmlibs.http.tools.EncryptionDecryptUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @Author: YY
 * @Date: 2021/4/10
 * @Description: 请求加密转换器
 */
public class EncryptRequestConverter<T> implements Converter<ResponseBody, T> {
    // 根据规范，加密请求的ContentType是application/x-www-form-urlencoded
    private static final MediaType MEDIA_TYPE = MediaType.get("application/x-www-form-urlencoded");
    private static final String UTF_8 = "UTF-8";
    private final Gson gson;
    private String clientPriKey;

    public EncryptRequestConverter(Gson gson, String clientPriKey) {
        this.gson = gson;
        this.clientPriKey = clientPriKey;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = gson.toJson(value);

        Map<String, Object> encryption = EncryptionDecryptUtils.encryption(json, clientPriKey);
        if (encryption != null) {
            StringBuilder buffer = new StringBuilder();
            String aesKey = URLEncoder.encode((String) encryption.get("aesKey"), UTF_8);
            buffer.append("aesKey=").append(aesKey).append('&');
            String data = URLEncoder.encode((String) encryption.get("data"), UTF_8);
            buffer.append("data=").append(data);
            return (T) RequestBody.create(buffer.toString(), MEDIA_TYPE);
        }
       return null;
    }

}
